<?php


namespace app\common\caches;


use Carbon\Carbon;
use think\facade\Cache;

class UserCache
{
    /**
     * 缓存恋人邀约Token
     * @param string $token     邀请token
     * @param object $user      本人信息对象
     * @return bool
     */
    public static function setInviteLoverToken(string $token, object $user) :void
    {
        $invite_token = 'invite.token';
        $invite_token_expire = 'invite.token.expire';
        Cache::store('redis')->handler()->hset($invite_token, $token, serialize($user));
        Cache::store('redis')->handler()->hset($invite_token_expire, $token, Carbon::now()->timestamp + 12 * 60 * 60);
    }

    /**
     * 获取恋人邀约Token
     * @param string $token     邀请token
     * @return bool
     */
    public static function getInviteLoverToken(string $token)
    {
        $invite_token = 'invite.token';
        $invite_token_expire = 'invite.token.expire';
        $expire_at = Cache::store('redis')->handler()->hget($invite_token_expire, $token);
        if (Carbon::now()->timestamp > $expire_at){
            Cache::store('redis')->handler()->hdel($invite_token, $token);
            Cache::store('redis')->handler()->hdel($invite_token_expire, $token);
            return null;
        }
        $user = Cache::store('redis')->handler()->hget($invite_token, $token);
        return unserialize($user);
    }

    /**
     * @todo 移除恋人邀约Token
     * @param string $token     邀请token
     * @return bool
     */
    public static function removeInviteLoverToken(string $token) :void
    {
        $invite_token = 'invite.token';
        $invite_token_expire = 'invite.token.expire';
        Cache::store('redis')->handler()->hdel($invite_token, $token);
        Cache::store('redis')->handler()->hdel($invite_token_expire, $token);
    }
}
